package Offer049;

/**
 * 从根节点到叶结点的路径数字之和
 *
 * @author 23737
 * @time 2021.12.19
 */
public class Test {
    public static void main(String[] args) {

    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

/**
 * dfs
 */
class Solution {
    int res = 0;

    public int sumNumbers(TreeNode root) {
        if (root == null) return res;
        dfs(root, 0);
        return res;
    }

    public void dfs(TreeNode root, int sum) {
        if (root == null) return;
        sum = sum * 10 + root.val;
        if (root.left != null) {
            dfs(root.left, sum);
        }
        if (root.right != null) {
            dfs(root.right, sum);
        }
        if (root.left == null && root.right == null) {
            res += sum;
        }
    }
}
